
package edu.upc.clase.demo.dao.impl;

import edu.upc.clase.demo.dao.SubcategoriaDao;
import edu.upc.clase.demo.entity.Subcategoria;
import java.util.List;
import javax.sql.DataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcDaoSupport;


public class SubcategoriaDaoImpl extends SimpleJdbcDaoSupport implements SubcategoriaDao {
    
    private static Logger log = LoggerFactory.getLogger(SubcategoriaDaoImpl.class);

    @Autowired
    public SubcategoriaDaoImpl(DataSource dataSource) {
        log.info("Asignando el dataSource");
        setDataSource(dataSource);
    }   
    
    @Override
    public Integer insertar(Subcategoria Subcategoria) {

        getJdbcTemplate().update(
                "insert into Subcategoria (de_Subcategoria,in_estado) values (?, ?, ?)",
                Subcategoria.getDescripcion(), Subcategoria.getEstado());
        return getSimpleJdbcTemplate().queryForInt("call identity()");
    }
    
    @Override
    public void actualizar(Subcategoria Subcategoria) {

        getJdbcTemplate().update(
                "update Subcategoria set de_Subcategoria = ? ,in_estado = ? where id_Subcategoria = ?",
                Subcategoria.getDescripcion(), Subcategoria.getEstado(), Subcategoria.getId());
       
    }
    
    @Override
    public void eliminar(Subcategoria Subcategoria) {

        getJdbcTemplate().update(
                "delete from Subcategoria where id_Subcategoria = ?)",
                Subcategoria.getId());
        
    }
    
            @Override
    public Subcategoria buscar(Integer id) {
        try {
            return getSimpleJdbcTemplate().queryForObject(
                    "select de_categoria,in_estado from Categorias where id_categoria=?",
                    new BeanPropertyRowMapper<Subcategoria>(Subcategoria.class), id);
        } catch (EmptyResultDataAccessException e) {
            return null;
        }
    }
    
    @Override
    public List<Subcategoria> buscarTodos() {
        return getSimpleJdbcTemplate().query(
                "select de_Subcategoria,in_estado from Subcategoria",
                new BeanPropertyRowMapper<Subcategoria>(Subcategoria.class));
    }    
    
    
}